package cn.melonlib.aap.user.comp.service;

import cn.melonlib.aap.user.model.entity.Account;
import cn.melonlib.aap.user.model.entity.Administrator;
import cn.melonlib.aap.user.model.enums.AccountType;
import cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService;
import cn.melonlib.cores.jpa.model.bean.impl.DefaultQuery;
import cn.melonlib.cores.model.anno.*;
import org.intellij.lang.annotations.Language;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;

@Service
@WorkerService(
        module = "user"
        ,model = @WorkerModel(
                modelType = Administrator.class
)
)
@WorkerComment("管理员管理")
public class AdministratorService extends WorkerBasicService<Administrator> {

    @Resource
    private AccountManagerService accountManagerService;

    @WorkerComment("创建管理员")
    @WorkerStore
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public Administrator createAdmin(
            @WorkerParameter(value = "administrator",comment = "管理员",required = true) Administrator administrator,
            @WorkerParameter(value = "password",comment = "密码",required = true) String password
    ) throws Exception{
        @Language("HQL") String validAdmin="from Administrator where code=?1";
        List<Administrator> administrators=dao.<List<Administrator>,DefaultQuery>search(new DefaultQuery(validAdmin,List.of(administrator.getCode()))).getResult();
        Assert.isTrue(administrators.isEmpty(),"账号已被占用");
        administrator=dao.save(administrator).getResult();
        Account account=new Account();
        account.setAccount(administrator.getCode());
        account.setTenant("melonlib");
        account.setTenantId("melonlib.cn");
        account.setActived(true);
        account.setAccountTypes(getJsonMapper().writeValueAsString(List.of(AccountType.ADMIN.name())));
        accountManagerService.createAccount(account,password);
        return administrator;
    }
}
